from marshmallow import Schema, fields, validate, validates, ValidationError, post_load
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from datetime import datetime
import sys
sys.path.append("/")
from app.extensions import db
from app.models.user import FinancialBusiness



class FinancialSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = FinancialBusiness  # 关联的数据库模型
        load_instance = True  # 反序列化时创建模型实例
        sqla_session = db.session  # 数据库会话
        dump_only = ("id", "created_at")  # 只读字段（禁止用户提交）
        include_fk = True  # 包含外键字段（未来扩展用）


    @validates("name")
    def validate_business_name(self, value, **_):
        """验证业务名称唯一性"""
        if FinancialBusiness.query.filter_by(name=value).first():
            raise ValidationError("业务名称已存在")

    @validates("dead_line")
    def validate_dead_line(self, value, **_):
        """验证截止日期有效性"""
        if value < datetime.utcnow():
            raise ValidationError("截止日期必须是将来的时间")

    @validates("content")
    def validate_content(self, value, **_):
        """验证内容有效性"""
        if len(value.strip()) == 0:
            raise ValidationError("内容不能为空")
        if len(value) > 255:
            raise ValidationError("内容长度不能超过255个字符")



class ManagerUpdateBusinessSchema(SQLAlchemyAutoSchema):
    name = fields.String(
        required=False
    )
    content = fields.String(
        required=False
    )
    dead_line = fields.DateTime(
        required=False
    )

    @validates("name")
    def validate_business_name(self, value, **_):
        """验证业务名称唯一性"""
        if FinancialBusiness.query.filter_by(name=value).first():
            raise ValidationError("业务名称已存在")

    @validates("content")
    def validate_content(self, value, **_):
        """验证内容有效性"""
        if len(value.strip()) == 0:
            raise ValidationError("内容不能为空")
        if len(value) > 255:
            raise ValidationError("内容长度不能超过255个字符")

    @validates("dead_line")
    def validate_dead_line(self, value, **_):
        """验证截止日期有效性"""
        if value < datetime.utcnow():
            raise ValidationError("截止日期必须是将来的时间")


financial_schema = FinancialSchema()
financiales_schema = FinancialSchema(many=True)
manager_update_business_schema = ManagerUpdateBusinessSchema()